<?php
/**
 * 直播后台
 * Created by PhpStorm.
 * User: 章利桂
 * Date: 2017/1/4
 * Time: 13:43
 */
class liveAdminController extends base
{
    public function __construct()
    {
        parent::__construct('admin');
        // 判断权限
        if(empty($this->realUser['uid']) || !$this->load('adminList')->isAdminByHupuUid($this->realUser['uid']))
        {
            echo 'jrs, 不要四处乱看哦～～';
            exit();
        }
    }

    public function doinit() {}

    /**
     * 微课列表
     */
    public function dogetList() {
        $arrStatus = common::$liveStatus;
        $name   = common::request('name','R','');//名称
        $status = isset($_REQUEST['status']) ? $_REQUEST['status'] : -999;//状态
        if ($status === '' || $status===null || $status==-999) {
            $status =-999;
        }
        $listNum = 20;
        $p = common::request('p', 'G', 1);
        $start = ($p - 1) * $listNum;
        $parameter = '';
        $params = [];
        if (trim($name)) {
            $parameter .= '&title='."$name";
            $params['name'] = $name;
        }
        if ($status <> -999) {
            $parameter .= '&status='."$status";
            $params['status'] = $status;
        }
        $params['start'] = $start;
        $params['limit'] = $listNum;
        $list = $this->load('live/live')->getList($params);
        if($list) {
            foreach ($list as $key=>$val) {
                $startTime2 = $val['start_time'] ? date('Y-m-d H:i:s',$val['start_time']) : '';
                $list[$key]['formatTime'] = $startTime2;
                $list[$key]['statusMsg'] = isset($arrStatus[$val['status']]) ? $arrStatus[$val['status']] : '未知状态';
                //礼物总值
                $list[$key]['totalGoldPrice'] = $this->db->getOne("select sum(`gold_price`) as totalGoldPrice from r_live_gold_list where live_id={$val['id']}  and `type`=2 and balance_type=0");
                //付费提问条数
                $list[$key]['totalQuesNum'] = $this->db->getOne("select count(1) from r_live_gold_list where live_id={$val['id']} and `type`= 1 and `balance_type`=0");
            }
        }
        $total = $this->load('live/live')->total;
        require FILE . 'lib/page.class.php';
        $page = new Page($total, $listNum, $parameter);
        $pageStr = $page->show();

        $this->view->assign('list', $list);
        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('name', $name);
        $this->view->assign('status', $status);
        $this->view->assign('arrStatus', $arrStatus);
        $this->view->display('live/liveList');
    }

    /**
     * 生成微课页面
     */
    public function doaddLive() {
        $liveId =  common::request('liveId','R',0);
        $arrInfo = [];
        if ($liveId) {
            $arrInfo = $this->load('live/live')->getLiveInfo($liveId);
            if (!$arrInfo) {
                common::tips('微课不存在');exit;
            }
            $arrInfo['formatStartTime'] = $arrInfo['start_time'] ? date('Y-m-d H:i:s',$arrInfo['start_time']) : '';
        }
        $this->view->assign('info', $arrInfo);
        $this->view->assign('liveId', $liveId);
        $this->view->display('live/addLive');
    }

    /**
     * 上传背景图
     */
    public function doajaxUploadImage() {
        if (!$_FILES || ($_FILES['imgFile']['size'] == 0)) {
            echo json_encode(array('status'=>'fail','error_msg'=>'请选择上传文件!'));
            exit;
        }
        $imageName ='live_thumb_'.md5(microtime(TRUE).$_FILES['imgFile']['name']);
        $image_url = $this->load('qiniu')->uploadQiNiuImg('imgFile',$imageName);
        if (!$image_url) {
            echo json_encode(array('status'=>'fail','error_msg'=>'上传失败'));exit;
        }
        echo json_encode(array('status'=>'ok','error_msg'=>'上传成功','image'=>$image_url));
    }

    /**
     * ajax生成微课
     */
    public function doajaxAddLive() {
        $id = common::request('liveId', 'R', 0);//微课ID
        $title = common::request('title', 'R', '');//微课标题
        $image = common::request('image', 'R', '');
        $price = common::request('price', 'R', '');//报名费
        $quesGoldNum = common::request('quesGoldNum', 'R', 0);//提问元宝数
        $startTime = common::request('startTime', 'R', 0);
        $speakerId = common::request('speakerId', 'R', 0);//主讲人ID
        $content = common::request('content', 'R', '');
        $limitNum = (int)common::request('limitNum', 'R', 0);//限制人数

        if (!trim($title)) {
            echo json_encode(array('status'=>'fail', 'error_msg'=>'微课标题必填'));exit;
        }
        if (!$image || !isset($image[0]) || !$image[0]) {
            echo json_encode(array('status'=>'fail', 'error_msg'=>'缩略图必传'));exit;
        }

        if($price && !preg_match('/^[0-9]*(\.[0-9]{1,2})?$/', $price, $match)){
            echo json_encode(array('status' => 'fail', 'error_msg' => '报名费必须为数字，最多2位小数'));exit;
        }
        if(!preg_match('/^(?:\d?\d|100)$/', $quesGoldNum, $match)){
            echo json_encode(array('status' => 'fail', 'error_msg' => '请输入0~100小元宝整数'));exit;
        }

        if (!trim($startTime)) {
            echo json_encode(array('status' => 'fail', 'error_msg' => '开始时间必填'));exit;
        }

        if (!trim($content)) {
            echo json_encode(array('status'=>'fail', 'error_msg'=>'详情必填'));exit;
        }

        //查询主讲人
        $arrSpeakerInfo = $this->load('live/live')->getSpeakerInfo($speakerId, 'id');
        if (!$arrSpeakerInfo) {
            echo json_encode(array('status'=>'fail', 'error_msg'=>'主讲人不存在，请先添加主讲人'));exit;
        }

        //查询更改的人数是否小于参与人数
        if($id > 0 && $limitNum > 0) {
            $arrInfo = $this->load('live/live')->getLiveInfo($id, 'join_num');
            if(!$arrInfo) {
                echo json_encode(array('status'=>'fail', 'error_msg'=>'微课不存在!'));exit;
            }
            if ($limitNum < $arrInfo['join_num']) {
                echo json_encode(array('status'=>'fail', 'error_msg'=>'微课更改的人数不能比参与人数小!'));exit;
            }
        }

        $fields = array();
        $fields['id'] = $id;
        $fields['title']     = $title;
        $fields['image']     = $image[0];
        $fields['startTime'] = $startTime;
        $fields['price']    = $price;
        $fields['quesGoldNum']    = $quesGoldNum;
        $fields['content'] = $content;
        $fields['speakerId']      = $speakerId;
        $fields['hostId']  = $this->realUser['uid'];
        $fields['limitNum']     = $limitNum;
        $result = $this->load('live/live')->addLive($fields);
        if ($result) {
            echo json_encode(array('status'=>'ok', 'error_msg'=>'操作成功','url'=>'index.php?c=live_admin&a=getList'));exit;
        }
        echo json_encode(array('status'=>'fail', 'error_msg'=>'操作失败'));
    }

    /**
     * 取消微课
     */
    public function doajaxDelLive() {
        $liveId = common::request('liveId', 'P', 0);
        $result = $this->load('live/live')->delLive($liveId);
        if ($result) {
            echo json_encode(array('status'=>'ok','error_msg'=>'操作成功'));exit;
        }
        echo json_encode(array('status'=>'fail','error_msg'=>'操作失败'));exit;
    }

    /**
     * 直播人列表
     */
    public function dogetspeakerList() {
        $listNum = 20;
        $p = common::request('p', 'G', 1);
        $start = ($p - 1) * $listNum;
        $parameter = '';
        $params = [];
        $params['start'] = $start;
        $params['limit'] = $listNum;
        $list = $this->load('live/live')->getSpeakerList($params);
        if($list) {
            foreach ($list as $key => $val) {
                $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'], 'header');
                $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'], 'nickname');
                $list[$key]['uid'] = $val['uid'];
                $list[$key]['nickname'] = $nickname;
                $list[$key]['header'] = $header;
            }
        }
        $total = $this->load('live/live')->total;
        require FILE . 'lib/page.class.php';
        $page = new Page($total, $listNum, $parameter);
        $pageStr = $page->show();
        $this->view->assign('list', $list);
        $this->view->assign('pageStr', $pageStr);
        $this->view->display('live/speakerList');
    }

    /**
     * ajax 创建直播人
     */
    public function doajaxAddSpeaker() {
        $uid = common::request('ids', 'R', 0);//微课ID
        if (!is_numeric($uid)) {
            echo json_encode(array('status'=>'fail', 'error_msg'=>'请填写注册的用户UID！'));exit;
        }
        $userInfo = $this->redis->hGetAll(REDIS_PREFIX . 'UserInfo_' . $uid);
        if (!$userInfo) {
            echo json_encode(array('status'=>'fail', 'error_msg'=>'请填写注册的用户UID！！'));exit;
        }

        $fields = array();
        $fields['uid']    = $uid;
        $fields['status']    = 0;
        $fields['create_time'] = time();
        $result = $this->load('live/live')->addSpeaker($fields);
        if ($result) {
            echo json_encode(array('status'=>'ok', 'error_msg'=>'操作成功','url'=>'index.php?c=live_admin&a=getSpeakerList'));exit;
        }
        echo json_encode(array('status'=>'fail', 'error_msg'=>'操作失败'));
    }

    /**
     * 移除直播人
     */
    public function doajaxDelSpeaker() {
        $speakerId = common::request('ids', 'P', 0);
        $result = $this->load('live/live')->delSpeaker($speakerId);
        if ($result) {
            echo json_encode(array('status'=>'ok','error_msg'=>'操作成功'));exit;
        }
        echo json_encode(array('status'=>'fail','error_msg'=>'操作失败'));exit;
    }

    /**
     * 元宝消费汇总
     */
    public function dogetGoldCostList() {
        $listNum = 20;
        $p = common::request('p', 'R', 1);
        $name   = common::request('name','R','');//名称
        $start = ($p - 1) * $listNum;
        $parameter = '';
        $params = [];
        $params['start'] = $start;
        $params['limit'] = $listNum;
        $params['name'] = $name;
        $list = $this->load('live/live')->getGoldCostList($params);
        if($list) {
            foreach ($list as $key=>$val) {
                $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'header');
                $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'nickname');
                $list[$key]['uid'] = $val['uid'];
                $list[$key]['nickname'] = $nickname;
                $list[$key]['header'] = $header;
                $info = $this->load('live/live')->getLiveInfo($val['live_id'], 'title');
                $list[$key]['title'] = $info['title'];
            }
        }
        $total = $this->load('live/live')->total;
        require FILE . 'lib/page.class.php';
        $page = new Page($total, $listNum, $parameter);
        $pageStr = $page->show();

        $this->view->assign('list', $list);
        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('name', $name);
        $this->view->display('live/goldSumList');
    }


}